﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace EdiNet
{
    public class EdiStreamWriter : IDisposable
    {
        StreamWriter sw;
        EdiReaderWriterSettings settings;

        public EdiStreamWriter(Stream ediStream, EdiReaderWriterSettings settings)
        {
            this.sw = new StreamWriter(ediStream, settings.EdiEncoding);
            this.settings = settings;
        }
        public void WriteSegment(DataSegment seg)
        {
            sw.Write(seg.SegId);
            int nEls = seg.Count();
            int nElSeparators = 1;
            for (int i = 1; i < nEls; ++i)
            {
                DataElement el = seg[i];
                string val = el[0];
                if (!string.IsNullOrEmpty(val))
                {
                    while (nElSeparators > 0)
                    {
                        sw.Write(settings.DataElementSeparatorChar);
                        --nElSeparators;
                    }
                    sw.Write(val);
                }
                int nComponents = el.Count();
                int nComponentSeparators = 1;
                for (int j = 1; j < nComponents; ++j)
                {
                    string valC = el[j];
                    if (!string.IsNullOrEmpty(valC))
                    {
                        while (nElSeparators > 0)
                        {
                            sw.Write(settings.DataElementSeparatorChar);
                            --nElSeparators;
                        }

                        while (nComponentSeparators > 0)
                        {
                            sw.Write(settings.ComponentSeparatorChar);
                            --nComponentSeparators;
                        }
                        sw.Write(valC);
                        ++nComponentSeparators;
                    }
                }
                ++nElSeparators;
            }
            sw.Write(settings.SegmentTerminatorChar);
        }
        public void Close()
        {
            sw.Close();
        }
        public void Dispose()
        {
            sw.Close();
        }
    }
}
